package cwb

import scala.collection.mutable.LinkedList
import scala.Console$
import scala.collection.mutable.MutableList
import java.io.PrintStream
import agent.Agent


object cwb extends App {
  // Debugging mode of the DWB
  var _debug = false
  
  def debug = _debug
  
  def toggleDebug() = _debug = !_debug
  
  /**
   * Println on the given string if debug mode is on.
   * @param string the string to print if debug is on.
   */
  def dbprintln(string: String) {
    if (_debug) println(string)
  }
  
  /**
   * Prints an line if debugging is set.
   */
  def dbprintln() {
    if (_debug) println
  }
  
  /**
   * Print on the given string if debug mode is on.
   * @param string the string to print if debug is on.
   */
  def dbprint(string: String) {
    if (_debug) print(string)
  }
  
  
  def listModules() {
    // List the loaded modules
    var modules = CWBModules.modules
    print("Modules loaded:")
    modules foreach {
      m => print(" \"" + m.name + "\"")
      }
    println()
  }
	
	// Registering modules.
  CWBModules.registerModule(CoreComponent)
  CWBModules.registerModule(Agent.component)
  // Register the commands from all the modules
  CWBModules.registerCommands()
  println("Welcome to the Edinburgh Concurrency Workbench") 
  listModules()
  
  var commandsPool: Commands[CommonCommand] = CWBCommands
  
	var currentCommand = ""

  System.out.print(commandsPool.commandLine)
  var done = true
	for(ln <- io.Source.stdin.getLines) {
	  var line = ln.split('\n')(0)
	  // Skip comment lines
	  if (line.length == 0 || (line.length > 0 && line(0) == '*')) {
	  } else {
	  if (line.takeRight(1) == ";") {
      currentCommand += line.take(line.length() -1)
      // Execute and reset the command.
      try {
        commandsPool.runCommand(currentCommand)
      } catch {
        case e: Error => System.out.println(e.message)
        case u: Unbound => System.out.println(u.message)
        case e: CWBParseException => System.out.println(if (_debug) e.message else "Parse error")
        case e: Panic => System.out.println("Something bad happened! Error: " + e.message)
      }
      currentCommand = ""
      done = true
    } else {
      currentCommand += line + " "
      done = false
    }
	  }
	  if (done) System.out.print(commandsPool.commandLine) else System.out.print("Continuation: ")

	}
	
	
}